package com.itheima.controller;

import com.itheima.contast.MessageConstant;
import com.itheima.entity.Result;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author Gallant
 * @create 2020-07-11 13:06
 */
@RestController
@RequestMapping("/user")
public class UserController {

    // 获取当前用户名
    @RequestMapping("/getUsername")
    public Result getUsername(){
        try {
            // 从security的域对象里边将user对象取出来
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_USERNAME_FAIL);
        }
    }

    @RequestMapping("/getUsername2")
    public Result getUsernam2(){
        // 创建一个map,用于存储返回数据(用户名和用户的权限)
        Map map = new HashMap<>();
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user != null){
            map.put("username",user.getUsername());
            Collection<GrantedAuthority> authorities = user.getAuthorities();
            Set<String> set = AuthorityUtils.authorityListToSet(authorities);
            map.put("authos",set);
            return new Result(true,MessageConstant.GET_USERNAME_SUCCESS,map);
        }
        return new Result(false,MessageConstant.GET_USERNAME_FAIL);
    }
}
